from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.conf import settings
from django.urls import reverse
from Crypto.PublicKey import RSA
from Crypto import Hash
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5  # 用于签名/验签


# 查看日K线图： http://image.sinajs.cn/newchart/daily/n/sh601006.gif
# 分时线的查询： http://image.sinajs.cn/newchart/min/n/sh000001.gif
# 日K线查询： http://image.sinajs.cn/newchart/daily/n/sh000001.gif
# 周K线查询： http://image.sinajs.cn/newchart/weekly/n/sh000001.gif
# 月K线查询： http://image.sinajs.cn/newchart/monthly/n/sh000001.gif

# 远程签名校验
from stocksys.views.views import init_message


def certificate_check(func):
    def sign_with_private_key(plain_text, private_key):
        # 私钥签名
        signer_pri_obj = sign_PKCS1_v1_5.new(RSA.importKey(private_key))
        rand_hash = Hash.SHA256.new()
        rand_hash.update(plain_text.encode())
        signature = signer_pri_obj.sign(rand_hash)
        return signature

    def verify_with_public_key(signature, plain_text):
        # 公钥验签
        verifier = sign_PKCS1_v1_5.new(settings.LOCAL_PUBLIC_RSA_KEY)
        _rand_hash = Hash.SHA256.new()
        _rand_hash.update(plain_text.encode())
        verify = verifier.verify(_rand_hash, signature)
        return verify  # true / false

    def warpper(request, *args, **kwargs):
        PRIVATE_RSA_KEY = request.session.get('PRIVATE_RSA_KEY', None)
        print("PRIVATE_RSA_KEY：",PRIVATE_RSA_KEY)
        print("settings.LOCAL_PUBLIC_RSA_KEY",settings.LOCAL_PUBLIC_RSA_KEY)
        if type(settings.LOCAL_PUBLIC_RSA_KEY) != type(None) and PRIVATE_RSA_KEY != None:
            verify_result=verify_with_public_key(sign_with_private_key(settings.SECRET_KEY, PRIVATE_RSA_KEY), settings.SECRET_KEY)
            print(verify_result)
            if verify_result:
                return func(request, *args, **kwargs)
        return HttpResponse("<button class='check_cert'></button>")
    return warpper


def certificate_login(request):
    return redirect(reverse('stocksys:stocksys_index'))

# 测试接口
@certificate_check
def test_demo(request):
    context = init_message()
    context["title"] = "量化分析系统-安全测试"
    return render(request, "stocksys/k_line.html", context)
